<template>
    <div>
        <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
            <template #field-deviceId="scope">
                <div class=" text-ellipsis line-clamp-1">
                    {{ isNullOrEmpty( formInline.deviceId ) }}
                </div>
            </template>
            <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
            <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
        </MyFormCreate>
        <div>
            <el-button v-auth="'business.monitor.channel-create'" type="primary" :icon="Plus"
                @click="add">添加通道</el-button>
                <el-button v-auth="'business.monitor.channel-create'" type="primary" 
                @click="joinInfo" plain>对接信息</el-button>
        </div>
        <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
            :isShowPag="false">
            <template #status="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'info'">
                    {{ isNullOrEmpty( row.status === 1 ? "在线" : "离线" ) }}
                </el-tag>
            </template>
            <template #action="{ row }">
                <el-space>
                    <sj-link custom-type="sblue" :underline="false" @click="infos(row)">播放</sj-link>
                    <sj-link v-auth="'business.monitor.channel-update'" custom-type="sblue" :underline="false"
                        @click="update(row)">编辑</sj-link>
                    <sj-link v-auth="'business.monitor.channel-delete'" custom-type="sred" :underline="false"
                        @click="del(row)">删除</sj-link>
                </el-space>
            </template>
        </pure-table>
        <div class="mt-5">
            <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
                :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList"
                @current-change="getTableList" />
        </div>
    </div>
</template>

<script setup lang="ts">
import joininfo from "./join-info.vue";
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import { PAGE_LAYOUT } from "@/constant";
import info from "./info.vue";
import { ref, reactive } from "vue";
import { deviceDetection } from "@pureadmin/utils";
import { addDialog } from "@/components/ReDialog";
import { VIDEOSTATUSS } from "@/constant/video-managemrnt";
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import { titles, defaultSearchFrom, prompt, defaultInfoForm } from './index';
import RePage from "@/components/RePage/index.vue";
import editForm from "./form.vue";
import settings from "../component/index.vue";
import { Plus, Delete } from '@element-plus/icons-vue';
import { message } from "@/utils/message";
import { ElMessage, ElMessageBox } from "element-plus";
import { joinDeviceInfo } from "@/api/operate/video-management/index";
import { videomonitorschannels, videomonitorschannelsadd, videomonitorschannelsinfo, videomonitorschannelsupdate, videomonitorschannelsdelete, videomonitorschannelsplay } from "@/api/operate/video-management/index";
import { debounce } from "@pureadmin/utils";
import { usePageVariablesStoreHook, UNIT_TYPE_VIEW_Map } from '@/store/modules/pageVariables'
import type { infoType } from '@/api/operate/video-management/index';
type FormProps = {
    formInline: infoType,
    isLoading: boolean,
}
const props = withDefaults(defineProps<FormProps>(), {
    formInline: () => ({} as infoType),
    isLoading: false,
});

const operate = usePageVariablesStoreHook().getOperate()
const searchFrom = ref(defaultSearchFrom());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
    data: [],
    total: 0,
});

const searchFormRules = [
    { type: "fieldComponent", field: "deviceId", title: '监控设备', value: null },
    {
        type: 'input', field: 'channelsId', title: titles.channelsId, value: null, props: {
            placeholder: prompt.channelsId, clearable: true
        }
    },
    {
        type: "select",
        field: "status",
        title: titles.status,
        value: null,
        options: VIDEOSTATUSS,
        props: {
            placeholder: prompt.status,
            clearable: true
        }
    },
    { type: 'number', field: 'page', title: 'page', hidden: true },
    { type: 'number', field: 'limit', title: 'limit', hidden: true },
];
const roleTableConfig = [
    // { type: "selection", align: "left" },
    { prop: 'id', label: titles.id, width:  100, fixed: 'left' },
    { prop: 'channelsName', label: titles.channelsName, minWidth: 100 },
    { prop: 'channelsId', label: titles.channelsId, minWidth: 100 },
    { slot: 'status', label: titles.status, minWidth: 100 },
    { prop: 'active', label: titles.active, minWidth: 160 },

    { slot: 'action', label: titles.action, width: 150, fixed: 'right' },
];
onMounted(() => {
    getTableList()
});



// 获取列表数据
const getTableList = () => {
    searchFrom.value.id = props.formInline.id
    videomonitorschannels(searchFrom.value).then(res => {

        if (res.code === 200) {
            tableData.data = res.result.data;
            tableData.total = res.result.total;
        }
    })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
    Object.assign(searchFrom.value, defaultSearchFrom())
    key.value++
    getTableList()
}

// 新增
const add = () => {
    showInfo.value = {}
    openDialog()
}
const update = row => {
    showInfo.value = {}
    openDialog("编辑通道", row);
}

// 删除
const del = (row) => {

    ElMessageBox.confirm(
        '确认删除这条数据?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            videomonitorschannelsdelete({ id: row.id }).then(res => {
                if (res.code == 200) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getTableList();
                }
            })
        })


}

// 播放
const infos = (row) => {
    videomonitorschannelsplay({
        channelsId: row.channelsId
    }).then(res => {
        if (res.code == 200) {
            addDialog({
                title: row.channelsName,
                width: "800px",
                draggable: true,
                fullscreen: deviceDetection(),
                fullscreenIcon: true,
                closeOnClickModal: false,
                hideFooter: true,
                props: {
                    isLoading: true,
                    formInline: row,
                    videoUrl: res.result.url,
                    playDuration: res.result.playDuration
                },
                contentRenderer: () => h(info, { ref: formRef }),

            });
        }
    })
}


// 开启弹窗
const openDialog = (title = "添加通道", row?: any) => {
    addDialog({
        title: `${title}`,
        width: "800px",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        props: {
            isLoading: false,
            originMarker: {},
            formInline: defaultInfoForm(),
        },
        contentRenderer: () => h(editForm, { ref: formRef }),
        openAutoFocus({ options, index }) {
            if (row) {  //编辑
                options.props = {
                    isLoading: true,
                    isEdit: true,
                    originMarker: {},
                    formInline: defaultInfoForm()
                }
                videomonitorschannelsinfo({ id: row.id }).then(res => {
                    if (res.code == 200) {
                        console.log(" res.result", res);
                        showInfo.value = res.result
                        options.props.formInline = res.result
                        options.props.originMarker = res.result.drawingPoint
                    }
                }).finally(() => {
                    options.props.isLoading = false
                })
            } else {  //添加
                options.props = {
                    isLoading: false,
                    isEdit: false,
                    formInline: defaultInfoForm()
                }

            }
        },
        beforeSure: (done, { options }) => {
            const FormRef = formRef.value.getRef();
            const formData = options.props.formInline;

            function chores() {
                message(`操作成功`, {
                    type: "success"
                });
                done(); // 关闭弹框
                getTableList(); // 刷新表格数据
            }
            FormRef.validate(valid => {
                if (valid && !options.props?.isLoading) {
                    // console.log("formData", formData);
                    // 表单规则校验通过
                    options.props.isLoading = true;
                    if (title === "添加通道") {
                        videomonitorschannelsadd({ ...formData, monitorId: props.formInline.id }).then(res => {
                            if (res.code == 200) {
                                chores();
                            }
                            options.props.isLoading = false;
                        }).catch((err) => {
                            if (err !== '请求中') {
                                options.props.isLoading = false;
                            }
                        })
                    } else {
                        videomonitorschannelsupdate({ ...formData, monitorId: props.formInline.id })
                            .then(res => {
                                if (res.code == 200) {
                                    chores();
                                }
                                options.props.isLoading = false;
                            })
                            .catch(err => {
                                if (err !== "请求中") {
                                    options.props.isLoading = false;
                                }
                            });
                    }
                }
            });
        }
    });
}

//对接信息
const joinInfo = () => {

addDialog({
  title: `对接信息`,
  width: "800px",
  draggable: true,
  fullscreen: deviceDetection(),
  fullscreenIcon: true,
  closeOnClickModal: false,
  hideFooter: true,
  props: {
    isLoading: true,
    formInline: {}
  },
  contentRenderer: () => h(joininfo, { ref: formRef }),
  openAutoFocus({ options, index }){
    joinDeviceInfo({id: props.formInline.id}).then(res => {
        options.props.formInline = res.result
        
    }).finally(() => {
                    options.props.isLoading = false
                })
  }

})
}
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
</script>

<style scoped></style>